package com.ltg.file.minio.config;

import com.ltg.file.exception.FileException;
import com.ltg.file.minio.properties.MinioProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import jakarta.annotation.Resource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p> ClassName: MinIoClientConfig </p>
 * <p> Package: com.ltg.file.minio.config </p>
 * <p> Description: </p>
 * <p></p>
 *
 * @Author: LTG
 * @Create: 2023/5/21 - 11:10
 * @Version: v1.0
 */

@Configuration
@EnableConfigurationProperties(
        MinioProperties.class
)
public class MinIoClientConfig {


    @Resource
    private MinioProperties minoProperties;

    /**
     * 注入minio 客户端
     *
     * @return
     */
    @Bean
    public MinioClient minioClient() {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minoProperties.getEndpoint())
                .credentials(minoProperties.getAccessKey(), minoProperties.getAccessSecret())
                .build();
        try {
            if(!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minoProperties.getBucketName()).build())){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minoProperties.getBucketName()).build());
            }
        } catch (Exception e) {
            throw new FileException(e.getMessage());
        }
        return minioClient;

    }
}
